package br.com.passeionaweb.appengine.tabelafipe;


import java.io.IOException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

import javax.jdo.PersistenceManager;
import javax.jdo.Query;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import br.com.passeionaweb.appengine.tabelafipe.data.DataProvider;
import br.com.passeionaweb.appengine.tabelafipe.data.Make;
import br.com.passeionaweb.appengine.tabelafipe.data.Model;
import br.com.passeionaweb.appengine.tabelafipe.data.PMF;
import br.com.passeionaweb.appengine.tabelafipe.data.Year;

import com.google.appengine.api.taskqueue.Queue;
import com.google.appengine.api.taskqueue.QueueFactory;
import com.google.appengine.api.taskqueue.TaskOptions;
import com.google.appengine.repackaged.org.json.JSONArray;
import com.google.appengine.repackaged.org.json.JSONException;
import com.google.appengine.repackaged.org.json.JSONObject;

@SuppressWarnings("serial")
public class UpdateYearsServlet extends HttpServlet {

	private static final PersistenceManager pm = PMF.get().getPersistenceManager();

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException,
			IOException {
		long start = Calendar.getInstance().getTimeInMillis();
		boolean result = updateYears();
		long end = Calendar.getInstance().getTimeInMillis();
		resp.getWriter().write("{result:"+result+",time:"+((end - start) / 1000)+"}");

	}

	@SuppressWarnings("unchecked")
	private boolean updateYears() {
		try {
			JSONArray jsonYears = new JSONArray(DataProvider.getYearsJSON());
			List<Year> years = new ArrayList<Year>();
			for (int i = 0; i < jsonYears.length(); ++i) {
				JSONObject jsonmake = jsonYears.getJSONObject(i);
				String yearName = jsonmake.getString(Year.KEY_YEAR);
				if (!Year.exists(yearName)) {
					years.add(new Year(yearName));
				}
				logPercentage(i, jsonYears.length());
			}
			if (years.size() != 0) {
				pm.makePersistentAll(years);
			}
			return true;
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return false;
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}
	}

	private void logPercentage(int done, int size) {
		float percentage = Float.valueOf(done) / Float.valueOf(size) * 100;
		System.out.println("Updating YEARS: " + percentage + "%");
	}
}
